console.log('[OcrPage] 导入React hooks: useState, useRef, useEffect');
import { useState, useRef, useEffect } from 'react';
console.log('[OcrPage] 导入lucide-react图标');
import { Copy, FolderOpen } from 'lucide-react';  // 移除未使用的FileText和Scan导入

console.log('[OcrPage] 导入FileUploadArea组件');
import FileUploadArea from '@/components/ocr/FileUploadArea';
console.log('[OcrPage] 导入PreviewArea组件');
import PreviewArea from '@/components/ocr/PreviewArea';
console.log('[OcrPage] 导入ResultEditor组件');
import ResultEditor from '@/components/ocr/ResultEditor';
console.log('[OcrPage] 导入ExportOptions组件');
import ExportOptions from '@/components/ocr/ExportOptions';
console.log('[OcrPage] 导入ProgressBar组件');
import ProgressBar from '@/components/ocr/ProgressBar';
console.log('[OcrPage] 导入callVlmModel工具函数');
import { callVlmModel, callPaddleOCR, callPaddleOCRForPDF, loadModelConfigs } from '@/lib/utils';
console.log('[OcrPage] 导入docx库组件');
import { Document, Packer, Paragraph, TextRun } from 'docx';
console.log('[OcrPage] 导入Tauri文件系统API');


console.log('[OcrPage] 定义UploadedFile接口');
interface UploadedFile {
  id: number;
  name: string;
  type: 'image' | 'pdf';
  size: string;
  date: string;
  url?: string; // 添加文件URL属性
  file?: File; // 添加原始文件对象
  savedPath?: string; // 添加保存路径属性
}

console.log('[OcrPage] 开始定义OcrPage组件函数');
export default function OcrPage() {

  console.log('[OcrPage] 初始化selectedFile状态为null');
  const [selectedFile, setSelectedFile] = useState<number | null>(null);
  // 初始化文件列表为空数组
  console.log('[OcrPage] 初始化uploadedFiles状态为空数组');
  const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([]);
  console.log('[OcrPage] 初始化recognitionResult状态为空字符串');
  const [recognitionResult, setRecognitionResult] = useState('');
  console.log('[OcrPage] 初始化isRecognizing状态为false');
  const [isRecognizing, setIsRecognizing] = useState(false);
  console.log('[OcrPage] 初始化recognitionProgress状态为0');
  const [recognitionProgress, setRecognitionProgress] = useState(0);
  console.log('[OcrPage] 初始化activeView状态为upload');
  const [activeView, setActiveView] = useState<'upload' | 'preview'>('upload');
  console.log('[OcrPage] 初始化imageSavePath状态为空字符串');
  const [imageSavePath, setImageSavePath] = useState('');
  console.log('[OcrPage] 初始化fileUrls引用为新的Map实例');
  const fileUrls = useRef<Map<number, string>>(new Map()); // 存储文件URL的引用


  // 从localStorage加载保存的图片路径
  useEffect(() => {
    console.log('[OcrPage] useEffect: 从localStorage加载图片保存路径');
    const savedPath = localStorage.getItem('imageSavePath') || './moreocr_files';
    console.log(`[OcrPage] 从localStorage获取到的保存路径: ${savedPath}`);
    setImageSavePath(savedPath);
    console.log('[OcrPage] 图片保存路径状态已更新');
  }, []);

  // 监听设置页面的路径变化
  useEffect(() => {
    console.log('[OcrPage] useEffect: 注册storage事件监听器');
    const handleStorageChange = (e: StorageEvent) => {
      console.log(`[OcrPage] 检测到storage变化事件: key=${e.key}, newValue=${e.newValue}`);
      if (e.key === 'imageSavePath') {
        console.log('[OcrPage] 图片保存路径发生变化，更新状态');
        setImageSavePath(e.newValue || '');
        console.log(`[OcrPage] 图片保存路径已更新为: ${e.newValue || ''}`);
      }
    };

    console.log('[OcrPage] 添加storage事件监听器');
    window.addEventListener('storage', handleStorageChange);
    return () => {
      console.log('[OcrPage] 移除storage事件监听器');
      window.removeEventListener('storage', handleStorageChange);
    };
  }, []);

  // 检查是否有激活的模型
  const hasActiveModel = () => {
    const { configs, status } = loadModelConfigs();
    if (!configs || !status) return false;
    
    const activeModelId = Object.keys(status).find(modelId => status[modelId]);
    return !!activeModelId;
  };

  // 替换模拟OCR识别过程
  const startRecognition = async (fileId?: number, targetFile?: UploadedFile, model?: string) => {
    console.log('[OcrPage] startRecognition函数被调用');
    console.log(`[OcrPage] 传入的fileId: ${fileId}`);
    console.log(`[OcrPage] 直接传入的文件: ${targetFile ? targetFile.name : '无'}`);
    console.log('[OcrPage] 设置isRecognizing为true');
    setIsRecognizing(true);
    console.log('[OcrPage] 设置recognitionProgress为30');
    setRecognitionProgress(30); // 初始进度

    try {
      console.log('[OcrPage] 开始识别流程');
      
      let selected: UploadedFile | undefined;
      
      if (targetFile) {
        // 如果直接传入了文件对象，直接使用
        selected = targetFile;
        console.log(`[OcrPage] 使用直接传入的文件: ${selected.name}`);
      } else {
        // 如果没有直接传入，则通过ID查找
        const targetFileId = fileId ?? selectedFile;
        console.log(`[OcrPage] 目标文件ID: ${targetFileId}`);
        selected = uploadedFiles.find(f => f.id === targetFileId);
        console.log(`[OcrPage] 通过ID找到的文件: ${selected ? selected.name : '未找到'}`);
      }
      
      if (!selected || !selected.file) {
        console.log('[OcrPage] 未找到选中的文件，抛出错误');
        throw new Error('未找到选中的文件');
      }

      console.log('[OcrPage] 设置recognitionProgress为60');
      setRecognitionProgress(60); // API调用中

      // 检查是否有激活的模型，如果没有则使用PaddleOCR
      const useVlm = model ? model !== 'paddleocr' : hasActiveModel();
      let result: string;
      
      if (useVlm && model && model !== 'paddleocr') {
        console.log(`[OcrPage] 使用指定模型${model}进行识别`);
        result = await callVlmModel(selected.file, model);
      } else {
        // 根据文件类型选择相应的OCR函数
        if (selected.type === 'pdf') {
          console.log('[OcrPage] 使用PaddleOCR PDF进行识别');
          result = await callPaddleOCRForPDF(selected.file);
        } else {
          console.log('[OcrPage] 使用PaddleOCR进行识别');
          result = await callPaddleOCR(selected.file);
        }
      }
      
      console.log('[OcrPage] 识别完成，更新结果');
      setRecognitionResult(result);
      console.log('[OcrPage] 设置recognitionProgress为100');
      setRecognitionProgress(100);
      console.log('[OcrPage] 设置activeView为preview');
      setActiveView('preview');
      console.log('[OcrPage] 识别流程完成');
    } catch (error) {
      console.error('[OcrPage] 识别失败:', error);
      alert(`识别失败: ${error instanceof Error ? error.message : String(error)}`);
    } finally {
      console.log('[OcrPage] 设置isRecognizing为false');
      setIsRecognizing(false);
    }
  };

  // 清理对象URL以避免内存泄漏

  // 创建目录的函数
  // 处理文件上传
  const handleFileUpload = async (files: FileList | null) => {
    console.log('[OcrPage] handleFileUpload函数被调用');
    console.log(`[OcrPage] 上传的文件数量: ${files ? files.length : 0}`);
    if (!files) {
      console.log('[OcrPage] 没有文件需要处理，直接返回');
      return;
    }
    
    console.log('[OcrPage] 开始处理文件上传');
    // // 创建默认目录
    // if (imageSavePath) {
    //   console.log(`[OcrPage] 准备创建目录: ${imageSavePath}`);
    //   await createDirectory(imageSavePath);
    //   console.log('[OcrPage] 目录创建完成');
    // }
    
    console.log('[OcrPage] 开始遍历处理每个文件');
    // 在实际应用中，这里会处理文件上传逻辑
    const fileArray = Array.from(files);
    console.log(`[OcrPage] 准备处理${fileArray.length}个文件`);
    
    // 使用for循环确保异步状态更新完成
    for (let i = 0; i < fileArray.length; i++) {
      const file = fileArray[i];
      console.log(`[OcrPage] 处理第${i + 1}个文件: ${file.name}`);
      console.log(`[OcrPage] 文件类型: ${file.type}, 文件大小: ${file.size}字节`);
      
      const fileType = file.type.startsWith('image/') ? 'image' : 'pdf';
      console.log(`[OcrPage] 文件类型判断结果: ${fileType}`);
      
      const newFile: UploadedFile = {
        id: Date.now() + Math.random(), // 确保ID唯一性
        name: file.name,
        type: fileType,
        size: `${(file.size / (1024 * 1024)).toFixed(1)}MB`,
        date: new Date().toLocaleDateString(),
        file: file
      };
      console.log(`[OcrPage] 创建新文件对象: ${JSON.stringify(newFile, null, 2)}`);
      
      console.log('[OcrPage] 为文件生成预览URL');
      const url = URL.createObjectURL(file);
      console.log(`[OcrPage] 生成的预览URL: ${url}`);
      fileUrls.current.set(newFile.id, url);
      newFile.url = url;
      console.log('[OcrPage] 预览URL已保存到fileUrls引用中');
      
      console.log('[OcrPage] 为图片文件添加保存路径');
      // 为图片文件添加保存路径
      if (fileType === 'image') {
        if (imageSavePath) {
          newFile.savedPath = `${imageSavePath}/${file.name}`;
          console.log(`[OcrPage] 图片保存路径: ${newFile.savedPath}`);
        } else {
          console.log('[OcrPage] 没有设置imageSavePath，跳过保存路径设置');
        }
      }
      
      // 等待状态更新完成
      await new Promise<void>((resolve) => {
        setUploadedFiles(prev => {
          console.log(`[OcrPage] 当前文件列表长度: ${prev.length}, 添加后长度: ${prev.length + 1}`);
          return [newFile, ...prev];
        });
        setSelectedFile(newFile.id);
        setActiveView('preview');
        
        // 使用setTimeout确保状态更新完成
        setTimeout(() => {
          resolve();
        }, 0);
      });
      
      console.log('[OcrPage] 开始为新文件进行识别');
      // 直接为新文件开始识别，传递文件对象
      await startRecognition(newFile.id, newFile);
      console.log(`[OcrPage] 文件${file.name}处理完成`);
    }
    console.log('[OcrPage] 所有文件处理完成');
  };



  // 处理导出
  const handleExport = (format: string) => {
    console.log('[OcrPage] handleExport函数被调用');
    console.log(`[OcrPage] 导出格式: ${format}`);
    console.log(`[OcrPage] 识别结果长度: ${recognitionResult.length}字符`);
    if (!recognitionResult) {
      console.log('[OcrPage] 没有识别结果，显示警告');
      alert('没有可导出的识别结果');
      return;
    }

    console.log('[OcrPage] 获取选中的文件名');
    // 获取选中的文件名作为基础名称
    const selected = uploadedFiles.find(f => f.id === selectedFile);
    console.log(`[OcrPage] 选中的文件: ${selected ? selected.name : '未找到，使用默认值'}`);
    const baseName = selected ? selected.name.replace(/\.[^/.]+$/, "") : "识别结果";
    let exportFileName = `${baseName}_识别结果.${format}`;
    console.log(`[OcrPage] 导出文件名: ${exportFileName}`);
    let blob: Blob | null = null;

    console.log(`[OcrPage] 开始处理${format}格式导出`);
    switch (format) {
      case 'txt':
        console.log('[OcrPage] 创建txt格式Blob');
        blob = new Blob([recognitionResult], { type: 'text/plain' });
        console.log('[OcrPage] txt格式Blob创建完成');
        break;
      case 'docx':
        console.log('[OcrPage] 创建docx格式文档');
        // 创建Word文档
        const doc = new Document({
          sections: [{
            properties: {},
            children: [
              new Paragraph({
                children: [
                  new TextRun(recognitionResult)
                ]
              })
            ]
          }]
        });
        console.log('[OcrPage] Word文档创建完成，准备转换为Blob');
        // 生成文档并转换为Blob
        Packer.toBlob(doc).then(generatedBlob => {
          console.log('[OcrPage] Word文档已转换为Blob');
          blob = generatedBlob;
          if (blob) {
            console.log('[OcrPage] 调用downloadFile进行下载');
            downloadFile(blob, exportFileName);
          }
        });
        console.log('[OcrPage] docx处理返回');
        return;
      case 'csv':
        console.log('[OcrPage] 创建csv格式内容');
        // 简单处理：将每行文本作为CSV的一行
        const csvContent = recognitionResult
          .split('\n')
          .map(line => line.replace(/,/g, '\,')) // 转义逗号
          .join('\n');
        console.log('[OcrPage] csv内容创建完成');
        blob = new Blob([csvContent], { type: 'text/csv' });
        console.log('[OcrPage] csv格式Blob创建完成');
        break;
      case 'json':
        console.log('[OcrPage] 创建json格式内容');
        const jsonContent = JSON.stringify({ content: recognitionResult }, null, 2);
        console.log('[OcrPage] json内容创建完成');
        blob = new Blob([jsonContent], { type: 'application/json' });
        console.log('[OcrPage] json格式Blob创建完成');
        break;
      case 'md':
        console.log('[OcrPage] 创建Markdown格式内容');
        const markdownContent = `# ${baseName} - OCR识别结果

## 文件信息
- **原始文件名**: ${baseName}
- **识别时间**: ${new Date().toLocaleString('zh-CN')}
- **识别引擎**: PaddleOCR

## 识别结果

${recognitionResult}

---
*由MoreOCR生成*`
        blob = new Blob([markdownContent], { type: 'text/markdown' });
        console.log('[OcrPage] Markdown格式Blob创建完成');
        break;
      default:
        console.log(`[OcrPage] 不支持的格式: ${format}`);
        alert(`暂不支持${format}格式导出`);
        return;
    }

    if (blob) {
      console.log('[OcrPage] 有可用Blob，准备下载');
      downloadFile(blob, exportFileName);
    } else {
      console.log('[OcrPage] 没有可用Blob，跳过下载');
    }
    console.log('[OcrPage] 导出处理完成');
  };

  // 查看保存的文件
  const handleViewSavedFiles = async () => {
    console.log('[OcrPage] handleViewSavedFiles函数被调用');
    try {
      // 使用Tauri的文件系统API打开保存目录
      const { open } = await import('@tauri-apps/plugin-dialog');
      const { join } = await import('@tauri-apps/api/path');
      
      // 获取保存目录路径
      const savePath = await join('.', 'moreocr_files');
      console.log(`[OcrPage] 保存目录路径: ${savePath}`);
      
      // 打开目录
      open({
        directory: true,
        defaultPath: savePath
      });
    } catch (error) {
      console.error('[OcrPage] 打开保存目录失败:', error);
      alert('打开保存目录失败，请确保已安装Tauri插件');
    }
  };

  // 提取下载文件的辅助函数
  const downloadFile = (blob: Blob, fileName: string) => {
    console.log('[OcrPage] downloadFile函数被调用');
    console.log(`[OcrPage] 下载文件名: ${fileName}`);
    console.log(`[OcrPage] Blob大小: ${blob.size}字节`);
    const url = URL.createObjectURL(blob);
    console.log(`[OcrPage] 创建的下载URL: ${url}`);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    console.log('[OcrPage] 创建并配置下载链接');
    document.body.appendChild(a);
    console.log('[OcrPage] 添加链接到文档');
    a.click();
    console.log('[OcrPage] 触发下载');
    document.body.removeChild(a);
    console.log('[OcrPage] 移除链接');
    URL.revokeObjectURL(url);
    console.log('[OcrPage] 清理URL');
  };

  // 处理复制结果
  const handleCopy = () => {
    console.log('[OcrPage] handleCopy函数被调用');
    console.log(`[OcrPage] 复制内容长度: ${recognitionResult.length}字符`);
    navigator.clipboard.writeText(recognitionResult);
    console.log('[OcrPage] 内容已复制到剪贴板');
    alert('识别结果已复制到剪贴板');
  };

  // 处理重新识别
  const handleReRecognize = (model: string) => {
    console.log('[OcrPage] handleReRecognize函数被调用');
    console.log('[OcrPage] 开始重新识别');
    if (selectedFile) {
      const file = uploadedFiles.find(f => f.id === selectedFile);
      if (file) {
        startRecognition(selectedFile, file, model);
      } else {
        console.error('[OcrPage] 重新识别时未找到文件');
      }
    }
    console.log('[OcrPage] 重新识别已启动');
  };

  // 监听文件上传事件
  useEffect(() => {
    const handleFileUploadEvent = (event: CustomEvent) => {
      const files = event.detail;
      if (files && files.length > 0) {
        handleFileUpload(files);
      }
    };

    document.addEventListener('fileUpload', handleFileUploadEvent as EventListener);
    
    return () => {
      document.removeEventListener('fileUpload', handleFileUploadEvent as EventListener);
    };
  }, [handleFileUpload]);

  // 监听系统托盘事件
  useEffect(() => {
    const handleTrayScreenshot = async () => {
    console.log('[OcrPage] 接收到托盘截图事件');
    // 调用Tauri截图API
    // 由于截图插件不可用，暂时移除截图逻辑
  };

    // 监听来自系统托盘的事件
    let unlisten: (() => void) | undefined;
    
    const setupEventListener = async () => {
      try {
        const { listen } = await import('@tauri-apps/api/event');
        unlisten = await listen('tray-screenshot', handleTrayScreenshot);
      } catch (error) {
        console.log('[OcrPage] 非Tauri环境，跳过托盘事件监听');
      }
    };

    setupEventListener();

    return () => {
      if (unlisten) {
        unlisten();
      }
    };
  }, []);  // 移除未定义的依赖项

  // 监听切换到上传视图事件
  useEffect(() => {
    const handleSwitchToUploadView = () => {
      console.log('[OcrPage] 接收到切换到上传视图事件');
      setActiveView('upload');
    };

    document.addEventListener('switchToUploadView', handleSwitchToUploadView as EventListener);
    
    return () => {
      document.removeEventListener('switchToUploadView', handleSwitchToUploadView as EventListener);
    };
  }, []);

  // 组件卸载时清理
  // useEffect(() => {
  //   return () => {
  //     cleanupFileUrls();
  //   };
  // }, []);

  return (
    <div className="flex flex-col h-screen bg-gray-50 overflow-hidden">
      {/* 顶部导航栏 */}
      <header className="bg-white border-b border-gray-200 py-3 px-4 flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <h1 className="text-xl font-bold text-gray-800">智能OCR识别</h1>
        </div>
        
        <div className="flex items-center space-x-3">
          {/* <button 
            className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-full"
            onClick={handleViewSavedFiles}
            title="查看保存的文件"
          >
            <FolderOpen className="w-5 h-5" />
          </button> */}
          {/* <button className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-full">
            <Settings className="w-5 h-5" />
          </button> */}
        </div>
      </header>



      <div className="flex flex-1 overflow-hidden">
        {/* 主内容区 */}
        <main className="flex-1 flex overflow-hidden">
          {/* 左侧上传/预览区 */}
          <div className="w-3/5 border-r border-gray-200 bg-gray-50 flex flex-col">
            {activeView === 'upload' ? (
              <FileUploadArea onFileUpload={handleFileUpload} />
            ) : (
              <PreviewArea 
              file={selectedFile ? uploadedFiles.find(f => f.id === selectedFile) ?? null : null}
              isRecognizing={isRecognizing}
              progress={recognitionProgress}
              onReRecognize={handleReRecognize}
              onSwitchToUploadView={() => setActiveView('upload')}
            />
            )}
          </div>

          {/* 右侧结果编辑区 */}
          <div className="w-2/5 bg-white flex flex-col">
            {isRecognizing ? (
              <div className="flex-1 flex flex-col items-center justify-center p-8">
                <div className="text-center mb-6">
                  {/* 移除未定义的Scan图标 */}
                  <h3 className="text-lg font-medium text-gray-700">正在识别文本内容</h3>
                  <p className="text-gray-500 mt-1">请稍候，我们正在处理您的文件</p>
                </div>
                <ProgressBar progress={recognitionProgress} className="w-full max-w-md" />
                <p className="text-sm text-gray-500 mt-2">{Math.round(recognitionProgress)}% 完成</p>
              </div>
            ) : recognitionResult ? (
              <>
                <div className="border-b border-gray-200 p-4 flex items-center justify-between">
                  <h2 className="text-lg font-semibold text-gray-800">识别结果</h2>
                  <div className="flex items-center space-x-2">
                    <button 
                      className="flex items-center text-sm text-gray-700 hover:text-blue-600"
                      onClick={handleCopy}
                    >
                      <Copy className="w-4 h-4 mr-1" />
                      复制
                    </button>
                    <ExportOptions onExport={handleExport} />
                  </div>
                </div>
                <div>
                  <ResultEditor content={recognitionResult} onChange={setRecognitionResult} />
                </div>
              </>
            ) : (
              <div className="flex-1 flex flex-col items-center justify-center p-8 text-center">
                <div className="bg-gray-100 p-6 rounded-full mb-4">
                  {/* 移除未定义的FileText图标 */}
                </div>
                <h3 className="text-lg font-medium text-gray-700 mb-1">暂无识别结果</h3>
                <p className="text-gray-500 max-w-md">上传文件并进行识别后，结果将显示在这里</p>
              </div>
            )}
          </div>
        </main>
      </div>
    </div>
  );
}
